/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 PerfTestServiceSyncImpl.cpp. Created on: 08.11.2010 13:13:45 
 */

#include "PerfTestServiceSyncImpl.hpp"

PerfTestServiceSyncImpl::PerfTestServiceSyncImpl() :
		m_nTps(0),
		m_nCurrentMeasureTime(time(NULL)),
		m_nCurrentRequestQueueSize(0),
		m_poStatisticThread(NULL),
		m_bStopFlag(false) {
	m_poStatisticThread = new boost::thread(
			boost::bind ( &PerfTestServiceSyncImpl::statisticThreadBody, this )
	);
}

PerfTestServiceSyncImpl::~PerfTestServiceSyncImpl() {
	m_bStopFlag=true;
	m_poStatisticThread->join();
	delete m_poStatisticThread;
}

ITestStructureType*  PerfTestServiceSyncImpl::testMethod(const std::string& paramStr ,  const boost::int32_t paramInt ,  ITestStructureType* paramStruct ,  const std::vector< ITestStructureType* > & paramArray)
	throw(IOException, SmartBusSystemException) {
	time_t nNow = time(NULL);
	//boost::unique_lock<boost::recursive_mutex> oLock(m_mxTps);
	++m_nTps;
	if(nNow > m_nCurrentMeasureTime + 5) {
		m_nCurrentMeasureTime = nNow;
		//oLock.unlock();
		m_nCurrentRequestQueueSize = ServerSkeleton::getCurrentRequestContext()->getSkeleton()->getRequestQueueSize();
	}
	else
		;//oLock.unlock();

	if(paramArray.empty())
		throw SmartBusSystemException("Incorrect array is received!");

	int nMaxRng = paramArray.size() - 1;
	if(nMaxRng<0)
		nMaxRng=0;
	//boost::uniform_int<> oRngAllowedMap(0,nMaxRng);
	//boost::variate_generator<boost::mt19937, boost::uniform_int<> > oRngGenerator(m_oRngType, oRngAllowedMap);
	//unsigned int idx = oRngGenerator();
	unsigned int idx = nMaxRng;
	ITestStructureType* poResult = paramArray[idx];
	poResult->addRef();
	return poResult;
}

void PerfTestServiceSyncImpl::statisticThreadBody() {
	while(!m_bStopFlag) {
		boost::this_thread::sleep(boost::posix_time::seconds(1));

		boost::unique_lock<boost::recursive_mutex> oLock(m_mxTps);
		unsigned int nTps = m_nTps;
		m_nTps = 0;
		oLock.unlock();
		std::cout << "TPS = " << nTps << ". Request queue: " << m_nCurrentRequestQueueSize << std::endl;
	}
}
